package elijah.eupdater;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.concurrent.TimeUnit;


import elijah.eupdater.bean.Result;
import elijah.eupdater.bean.TerminalDevice;
import elijah.eupdater.utils.AppUtils;
import io.reactivex.Observable;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class UpdateService extends Service {
    public static final String PUSH_UPDATE_APP = "push_update_app";
    private final CompositeDisposable disposable = new CompositeDisposable();
    private NetApi netApi;

    public static final String CHANNEL_UPDATE_SERVICE = "update_service";


    private Notification notification;

    private final TerminalDevice terminalDevice = new TerminalDevice();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            initNotification();
        }
        netApi = NetApi.Creator.create(Eupdater.get().getConfig().getHost());
        LiveEventBus.get(PUSH_UPDATE_APP, boolean.class).observeForever(aBoolean -> startLoop());
        Log.e("TAG", "onCreate: ");

        startLoop();

    }

    private void initNotification() {

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_UPDATE_SERVICE, "ELIJAH更新服务", NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(getApplicationContext(), CHANNEL_UPDATE_SERVICE).build();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
            } else {
                startForeground(1, notification);

            }
        }

    }


    public void startLoop() {
        disposable.clear();
        disposable.add(Observable.interval(5, Eupdater.get().getConfig().getLoopTime(), TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io()).subscribe(aLong -> updateTerminal()));
    }

    private void updateTerminal() {
        Log.e("TAG", "updateTerminal: ");

        terminalDevice.setDeviceId(AppUtils.getAndroidId(this)).setPackageName(getApplicationContext().getPackageName()).setVersionCode(AppUtils.getAppVersionCode(this)).setVersionName(AppUtils.getAppVersionName(this)).setDeviceIp(AppUtils.getIpAddressString());

        netApi.updateTerminalInfo(terminalDevice).subscribeOn(Schedulers.io()).subscribe(new SingleObserver<Result<TerminalDevice>>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposable.add(d);
            }

            @Override
            public void onSuccess(Result<TerminalDevice> terminalDeviceResult) {
                if (terminalDeviceResult.getCode() == 0) {
                    if (AppUtils.getAppVersionCode(getContext()) < terminalDeviceResult.getData().getUpdateVersionCode() && !TextUtils.isEmpty(terminalDeviceResult.getData().getUpdateFilePath())) {
                        netApi.startUpdate(terminalDevice.getDeviceId(), terminalDevice.getPackageName())
                                .subscribeOn(Schedulers.io())
                                .subscribe(new SingleObserver<Result>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {
                                        disposable.add(d);
                                    }

                                    @Override
                                    public void onSuccess(Result result) {
                                        if (result.getCode() == 0) {
                                            LiveEventBus.get(UpdateActivity.KEY_DATA, TerminalDevice.class).post(terminalDeviceResult.getData());
                                            Intent intent = new Intent(getContext(), UpdateActivity.class);
                                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            getContext().startActivity(intent);
                                            disposable.clear();
                                            stopSelf();
                                        }

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        e.printStackTrace();

                                    }
                                });

                    }
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }
        });
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }


    public Context getContext() {
        return this;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        disposable.clear();
    }
}
